import './avatarUploader.scss';

function avatarUploaderComponent($compile, uiUploader1, $log, $rootScope) {
  'ngInject';

  return {
    restrict: 'A',
    scope: {
      ngModel: '=',
      url: '@',
    },
    compile(tElement, tAttrs) {
      const fileInput = angular.element('<input class="invisible" type="file" accept="image/*" name="file" id="file" />');
      angular.element(document.body).append(fileInput);
      tElement.prepend('<span class="avatar-upload-tip" style="display: none">上传失败</span>');

      return function link(scope, iElement, iAttrs) {
        const context = '/sgms';
        let url = scope.url || '/api/v1/common/uploadFile?folderName=common';
        url = context + url;
        tElement.click((e) => {
          if (e.target.tagName === 'INPUT') {
            e.stopPropagation();
          } else {
            fileInput.click();
          }
        });

        fileInput.change((e) => {
          const files = e.target.files;
          uiUploader1.addFiles(files);
          if (files && files[0]) {
            scope.ngModel = files[0];
          }
          scope.$apply();

          const reader = new FileReader();
          reader.onload = () => {
            const dataUrl = reader.result;
            iElement.find('img').attr('src', dataUrl);
          };
          reader.readAsDataURL(scope.ngModel);

          fileInput.val('');
          angular.element('.avatar-upload-tip').hide();
          uiUploader1.startUpload({
            url,
            concurrency: 2,
            onProgress(file) {
              if (!file.isUploading) {
                file.isUploading = true;
              }
              $log.info(`${file.name}=${file.humanSize}`);
              scope.$apply();
            },
            onCompleted(file, responseTxt) {
              const resp = JSON.parse(responseTxt);
              if (resp.success) {
                file.id = resp.data;
              } else {
                angular.element('.avatar-upload-tip').show();
              }
              file.isUploading = false;
              scope.$apply();
              $log.info(`${file} upload completed , ${responseTxt}`);
            },
          });
        });
      };
    },
  };
}

export default avatarUploaderComponent;
